package com.ly.blog_article.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ly.blog_article.vo.InfoMapVo;
import com.ly.blog_article.entity.LabelEntity;
import com.ly.blog_article.service.InfoService;
import com.ly.blog_article.service.LabelService;
import com.ly.blog_article.vo.InfoShowVo;
import com.ly.blog_common.entity.InfoEntity;
import com.ly.blog_common.excel.ExcelCore;
import com.ly.blog_common.excel.ExcelExportType;
import com.ly.blog_common.security.SecurityUtils;
import com.ly.blog_common.utils.ExcelUtils;
import com.ly.blog_common.utils.PageUtils;
import com.ly.blog_common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;



/**
 * 
 *
 * @author liyang
 *
 * @date 2021-06-12 15:45:28
 */
@RestController
@RequestMapping("article/info")
public class InfoController {
    @Autowired
    private InfoService infoService;
    @Autowired
    private LabelService labelService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('article:info:list')")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = infoService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 地图坐标集合列表
     */
    @RequestMapping("/list/map")
    public R listMap(@RequestParam Map<String, Object> params){
        List<InfoMapVo> data = infoService.listMap(params);

        return R.ok().put("data", data);
    }

    /**
     * excel导出
     * @param params
     * @return
     */
    @RequestMapping("/list/excel")
//    @PreAuthorize("hasAuthority('article:info:list')")
    public R listExcel(@RequestParam Map<String, Object> params,
                       HttpServletResponse response,
                       HttpServletRequest request){
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.orderBy(true,false,"create_time");
            List<InfoEntity> list = infoService.list(queryWrapper);
            ExcelUtils.excelExport("文章列表",InfoEntity.class,list,new ExcelCore(),
                    ExcelExportType.EXPORT_TYPE,response,request);
        } catch (IOException e) {
            return R.error("导出文章excel失败");
        }
        return null;
    }

    /**
     * 展示列表
     */
    @RequestMapping("/show/list")
    public R showList(@RequestParam Map<String, Object> params){
        PageUtils page = infoService.queryShowPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 检索列表
     */
    @RequestMapping("/search/list")
    public R searchList(@RequestParam Map<String, Object> params){
        PageUtils page = infoService.querySearchPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 全部列表
     */
    @RequestMapping("/list/all")
    @PreAuthorize("hasAuthority('article:info:list')")
    public R listAll(){
        List<InfoEntity> infoEntities = infoService.listAll();

        return R.ok().put("infoList", infoEntities);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @PreAuthorize("hasAuthority('article:info:info')")
    public R info(@PathVariable("id") Long id){
		InfoEntity info = infoService.getById(id);

        return R.ok().put("info", info);
    }

    /**
     * 展示信息
     */
    @RequestMapping("/show/info/{id}")
    public R showInfo(@PathVariable("id") Long id){
		InfoShowVo showInfo = infoService.getShowById(id);

		//增加浏览记录
        InfoEntity info = infoService.getById(id);
        info.setWatchTime(info.getWatchTime() + 1);
        boolean update = infoService.updateById(info);

        return R.ok().put("showInfo", showInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @PreAuthorize("hasAuthority('article:info:save')")
    public R save(@RequestBody InfoEntity info){

        //针对新增标签，添加到数据库并回执处理
        if(null != info.getLabelId()) {
            info.setLabelId(checkLabelAndAddReplace(info.getLabelId()));
        }

        info.setCreateBy(SecurityUtils.getUserId());
        info.setCreateTime(new Date());
        info.setLastUpdateBy(SecurityUtils.getUserId());
        info.setLastUpdateTime(new Date());
		infoService.save(info);

        return R.ok().put("id",info.getId());
    }

    /**
     * 检测新增标签并添加到数据库和替换
     * @param labelId
     * @return
     */
    private String checkLabelAndAddReplace(String labelId) {

        String[] split = labelId.split(",");
        List<LabelEntity> labelEntities = labelService.listAll();
        for(String item : Arrays.asList(split)){
            boolean isAdd = true;
            for (LabelEntity labelEntity : labelEntities) {
                String id = labelEntity.getId().toString();
                if(item.equals(id)){
                    isAdd = false;
                    break;
                }
            }
            if(isAdd){
                LabelEntity labelEntity = new LabelEntity();
                labelEntity.setName(item);

                labelEntity.setCreateBy(SecurityUtils.getUserId());
                labelEntity.setCreateTime(new Date());
                labelEntity.setLastUpdateBy(SecurityUtils.getUserId());
                labelEntity.setLastUpdateTime(new Date());
                labelService.save(labelEntity);
                LabelEntity labelEntity1 = labelService.getOne(new QueryWrapper<LabelEntity>().eq("name",item));
                String idNew = labelEntity1.getId().toString();
                labelId = labelId.replace(item, idNew);
            }
        }
        return labelId;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @PreAuthorize("hasAuthority('article:info:update')")
    public R update(@RequestBody InfoEntity info){

        //针对新增标签，添加到数据库并回执处理
        if(null != info.getLabelId()) {
            info.setLabelId(checkLabelAndAddReplace(info.getLabelId()));
        }

        info.setLastUpdateBy(SecurityUtils.getUserId());
        info.setLastUpdateTime(new Date());
		infoService.updateById(info);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('article:info:delete')")
    public R delete(@RequestBody Long[] ids){
		infoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
